package com.wugh.fast.module.web.deserializer;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdScalarDeserializer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.Date;

/**
 * 说明: jackson的 date自动转化
 *
 * @author wugh
 * @date 2019-01-26 10:30
 */
@Slf4j
public class DateDeserializer extends StdScalarDeserializer<Date> {
    public DateDeserializer() {
        super(Date.class);
    }

    @Override
    public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        String text = p.getValueAsString();
        if (StringUtils.isBlank(text)) {
            return null;
        }
        try {
            DateTime dateTime = DateUtil.parse(text);
            return dateTime.toJdkDate();
        } catch (Exception e) {
            //报错,则可能是纯数字的时间戳
            try {
                return new Date(Long.parseLong(text));
            } catch (NumberFormatException ex) {
                log.debug("日期转换失败:{}", text);
                return null;
            }
        }
    }
}
